<template>
  <el-dialog
    :title="$t('taskDialog.title.create')"
    :visible.sync="taskCreatedBatchDialogVisible"
    width="80%"
    top="70px"
    :before-close="closeDialogCan"
    @open="open()"
    ref="dialogRef"
    id="myDialog"
  >
    <span class="main">
      <!-- @row-click="editor" -->
      <el-table
        :data="taskCreatedBatchList"
        style="width: 100%"
        :row-class-name="tableRowClassName"
        @row-click="editor"
      >
        <el-table-column type="index" :label="$t('taskDialog.table.index')">
        </el-table-column>
        <el-table-column
          prop="projectName"
          :label="$t('taskDialog.table.proName')"
        >
          <template slot-scope="{ row }">
            <span v-show="!isEditor[row.index]">{{
              row.projectName.name
            }}</span>
            <el-select
              v-show="isEditor[row.index]"
              v-model="row.projectName"
              :placeholder="$t('taskDialog.table.select')"
              size="small"
              value-key="id"
              @change="selectChange(row)"
            >
              <el-option
                v-for="item in projectList"
                :key="item.id"
                :label="item.name"
                :value="item"
              >
              </el-option>
            </el-select>
            <div v-show="row.proVisible" style="font-size: 6px; color: #f56c6c">
              {{ $t("taskDialog.valid.project") }}
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="taskName"
          :label="$t('taskDialog.table.taskName')"
        >
          <template slot-scope="{ row }">
            <span v-show="!isEditor[row.index]">{{ row.taskName }}</span>
            <el-input
              v-show="isEditor[row.index]"
              v-model="row.taskName"
              :placeholder="$t('taskDialog.table.placeholder')"
              size="small"
              @blur="iptBlur(row)"
              class="redInput"
            ></el-input>
            <div
              v-show="row.taskVisible"
              style="font-size: 6px; color: #f56c6c"
            >
              {{ $t("taskDialog.valid.task") }}
            </div>
            <div
              v-show="row.checkVisible"
              style="font-size: 6px; color: #f56c6c"
            >
              任务名不能重复
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="reptile"
          width="180px"
          :label="$t('taskDialog.table.reptile')"
          show-overflow-tooltip
        >
          <template slot-scope="{ row }">
            <!-- 将数组转换为字符串并以逗号分隔 -->
            <!-- {{
              row.reptile[row.index].en_name
            }} -->
            <span class="reptileSpan" v-show="!isEditor[row.index]">
              <!-- 通过处理 得到对象中的en_name -->
              {{
                row.reptile
                  .map((val) => {
                    return val.en_name;
                  })
                  .join(",")
              }}
            </span>
            <el-select
              collapse-tags
              filterable
              multiple
              v-show="isEditor[row.index]"
              v-model="row.reptile"
              value-key="id"
              :placeholder="$t('taskDialog.table.select')"
              size="small"
            >
              <el-option
                v-for="item in proReptileList"
                :key="item.id"
                :label="item.en_name"
                :value="item"
              >
              </el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column
          prop="hostName"
          :label="$t('taskDialog.table.hostName')"
        >
          <template slot-scope="{ row }">
            <span v-show="!isEditor[row.index]">{{ row.hostName.name }}</span>
            <el-input
              disabled
              v-show="isEditor[row.index]"
              v-model="row.hostName.name"
              :placeholder="$t('taskDialog.table.placeholder')"
              size="small"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="ip" :label="$t('taskDialog.table.hostIP')">
          <template slot-scope="{ row }">
            <span v-show="!isEditor[row.index]">{{ row.ip }}</span>
            <el-input
              disabled
              v-show="isEditor[row.index]"
              v-model="row.ip"
              :placeholder="$t('taskDialog.table.placeholder')"
              size="small"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="time" :label="$t('taskDialog.table.time')">
          <template slot-scope="{ row }">
            <el-button type="text" @click="configTime(row)">{{
              $t("taskDialog.btn.time")
            }}</el-button>
          </template>
        </el-table-column>
        <el-table-column prop="note" :label="$t('taskDialog.table.descript')">
          <template slot-scope="{ row }">
            <span v-show="!isEditor[row.index]">{{ row.note }}</span>
            <el-input
              v-show="isEditor[row.index]"
              v-model="row.note"
              :placeholder="$t('taskDialog.table.placeholder')"
              size="small"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column :label="$t('taskDialog.table.del')">
          <template slot-scope="{ row }">
            <el-button
              type="danger"
              size="small"
              plain
              icon="el-icon-delete"
              @click="del(row)"
              >{{ $t("taskDialog.btn.del") }}</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-button
        type="success"
        plain
        icon="el-icon-circle-plus-outline"
        style="width: 100%"
        @click="newCreatedTask"
        >{{ $t("taskDialog.btn.add") }}</el-button
      >
    </span>
    <span slot="footer" class="dialog-footer">
      <!-- <el-button type="text" @click="noEditor">取消编辑状态</el-button> -->
      <el-button @click="closeDialogCan">{{
        $t("taskDialog.btn.cancel")
      }}</el-button>
      <el-button type="primary" @click="createdTask">{{
        $t("taskDialog.btn.create")
      }}</el-button>
    </span>
    <TaskCreatedBatchInnerDialog
      :taskCreatedBatchInnerDialogVisible="taskCreatedBatchInnerDialogVisible"
      :isInner="isInner"
      :createdDataRow="createdDataRow"
      :taskCreatedBatchList="taskCreatedBatchList"
      :createdDataIndex="createdDataIndex"
      @saveTime="saveTime"
      @closeDialog="closeInnerDialog"
    ></TaskCreatedBatchInnerDialog>
  </el-dialog>
</template>

<script>
import TaskCreatedBatchInnerDialog from "./TaskCreatedBatchInnerDialog.vue";
export default {
  components: { TaskCreatedBatchInnerDialog },
  props: [
    "taskCreatedBatchDialogVisible",
    "projectList",
    "hostList",
    "reptileList",
  ],
  data() {
    return {
      // 判断任务名是否重复 和 项目名是否为空
      taskInput: false,
      projectInput: false,
      // 控制配置时间对话框的显示与隐藏
      taskCreatedBatchInnerDialogVisible: false,
      // 判断是否为嵌套对话框
      isInner: true,
      text: "",
      // 创建的任务列表
      taskCreatedBatchList: [
        {
          configuration: "", // 配置时间
          projectName: "",
          taskName: "",
          reptile: [],
          hostName: "",
          ip: "",
          note: "",
          proVisible: false,
          taskVisible: false,
          checkVisible: false,
        },
      ],
      // 点击创建任务时 向后台发送的数据
      createdTaskForm: [],
      // 是否编辑
      isEditor: [],
      // 整行数据
      createdDataRow: "",
      // 整行数据的索引
      createdDataIndex: "",
      // 爬虫只能是该项目下的爬虫
      proReptileList: [],
    };
  },
  methods: {
    // 打开对话框
    open() {
      console.log(this.reptileList);
      this.isEditor[0] = true;
      // 点击其他地方 表格所有input失去焦点（待完善）
      document.querySelector("#myDialog").addEventListener("click", (e) => {
        if (
          e.target.className == "el-dialog__header" ||
          e.target.className == "el-dialog__footer"
        ) {
          this.isEditor = [];
        }
      });
    },
    // 行的 className 的回调方法
    tableRowClassName({ row, rowIndex }) {
      // 使用这个方法 可以将行的索引添加到行数据row中
      row.index = rowIndex;
      row.isEditor = "false";
    },
    // 点击整行编辑
    editor(row, col, e) {
      // 巧妙地运用点击事件 实现点击行可编辑
      this.isEditor = [];
      this.taskCreatedBatchList.forEach(() => {
        this.isEditor.push(false);
      });
      this.isEditor[row.index] = true;
    },
    // 项目发生变化时
    selectChange(row) {
      console.log(row.projectName.type);
      row.reptile = [];
      console.log(row);
      row.proVisible = false;
      if (row.taskName != "" && row.taskName !== undefined) {
        this.taskCheckTab(row);
      } else {
        row.taskVisible = true;
      }
      let res = this.hostList.filter((val) => {
        return val.id == row.projectName.client_id;
      });
      row.ip = res[0].ip;
      row.hostName = res[0];
      console.log(res);

      // 项目发生变化时 才能显示该项目下的爬虫
      console.log(row.projectName.id);
      this.proReptileList = this.reptileList.filter((val) => {
        return val.project_id == row.projectName.id;
      });
      console.log(this.proReptileList);
    },
    // 删除
    del(row) {
      this.taskCreatedBatchList.splice(row.index, 1);
    },
    // 新建任务按钮
    newCreatedTask() {
      // 点击添加任务 默认创建一个和上面一条任务数据差不多的任务
      let index;
      let newProjectName;
      let newTaskName;
      let newHostName;
      let newIp;
      if (this.taskCreatedBatchList.length != 0) {
        index = this.taskCreatedBatchList.length - 1;
        if (this.taskCreatedBatchList[index].projectName == "") {
          this.taskCreatedBatchList[index].proVisible = true;
        }
        if (!this.taskCreatedBatchList[index].taskName) {
          this.taskCreatedBatchList[index].taskVisible = true;
        }
        newProjectName = this.taskCreatedBatchList[index].projectName;
        // newTaskName = this.taskCreatedBatchList[index].taskName;
        newHostName = this.taskCreatedBatchList[index].hostName;
        newIp = this.taskCreatedBatchList[index].ip;
      } else {
        newProjectName = "";
        // newTaskName = "";
        newHostName = "";
        newIp = "";
      }
      this.taskCreatedBatchList.push({
        projectName: newProjectName,
        taskName: newTaskName,
        reptile: [],
        hostName: newHostName,
        ip: newIp,
        configuration: "", // 配置时间
        note: "",
        proVisible: false,
        taskVisible: false,
        checkVisible: false,
      });
      // console.log(this.taskCreatedBatchList.length);
    },
    // 创建任务按钮
    async createdTask() {
      let isSend = [];
      this.taskCreatedBatchList.forEach((val, index, arr) => {
        // 判断任务名是否为空
        if (val.taskName == "" || val.taskName === undefined) {
          val.taskVisible = true;
        } else {
          // 判断该项目下是否已经有了这个任务名
          if (val.projectName != "") {
            this.taskCheckTab(val);
          }
        }
        // 判断项目是否为空
        if (!val.projectName || val.projectName == "") {
          val.proVisible = true;
        }
        // 只有当所有值填写正确 时 才发送请求
        if (val.proVisible || val.taskVisible || val.checkVisible) {
          isSend.push("1");
        }

        this.createdTaskForm[index] = {};
        this.createdTaskForm[index].project_id = val.projectName.id;
        this.createdTaskForm[index].name = val.taskName;
        this.createdTaskForm[index].spider = val.reptile.map((vals) => {
          return vals.id;
        });
        this.createdTaskForm[index].clients = val.hostName.id;
        this.createdTaskForm[index].configuration = val.configuration;
        this.createdTaskForm[index].description = val.note;
        this.createdTaskForm[index].type = val.projectName.type;
      });
      if (isSend.length != 0) {
        this.$message.error(this.$t("taskDialog.message.paramsError"));
      } else {
        const { data: res } = await this.$http.post(
          "/task/created",
          this.createdTaskForm
        );
        if (res.code != 0)
          return this.$message.error(this.$t("taskDialog.message.createError"));
        this.$message.success(this.$t("taskDialog.message.createSuccess"));
        (this.taskCreatedBatchList = [
          {
            configuration: "", // 配置时间
            projectName: "",
            taskName: "",
            reptile: [],
            hostName: "",
            ip: "",
            note: "",
            proVisible: false,
            taskVisible: false,
            checkVisible: false,
          },
        ]),
          this.closeDialog();
      }
    },
    // 配置时间按钮
    configTime(row) {
      console.log(row);
      this.createdDataIndex = row.index;
      this.createdDataRow = row;
      this.taskCreatedBatchInnerDialogVisible = true;
    },
    // 配置时间保存
    saveTime(val, index) {
      console.log(val, index);
      // 将配置的时间添加到对应的任务中
      this.taskCreatedBatchList.find((ele) => {
        return ele.index == index;
      }).configuration = val;
      console.log(this.taskCreatedBatchList);
    },
    // 任务查重（数据库查重）
    async taskCheck(row, name, id) {
      const { data: res } = await this.$http.get("/check/task/name", {
        params: {
          name: name,
          project_id: id,
          type: 0,
        },
      });
      if (res.code == 1) {
        row.checkVisible = true;
      } else if (res.code == 0) {
        row.checkVisible = false;
      }
    },
    // 任务查重（页面查重）
    taskCheckTab(row) {
      let taskRepeat = this.taskCreatedBatchList.filter((val) => {
        return val.taskName == row.taskName;
      });
      if (taskRepeat.length > 1) {
        let proRepeat = taskRepeat.filter((val) => {
          return val.projectName.id == row.projectName.id;
        });
        if (proRepeat.length > 1) {
          row.checkVisible = true;
        } else {
          this.taskCheck(row, row.taskName, row.projectName.id);
        }
      } else {
        this.taskCheck(row, row.taskName, row.projectName.id);
      }
    },
    // 任务输入框失去焦点时
    async iptBlur(row) {
      if (row.taskName == undefined || row.taskName == "") {
        row.taskVisible = true;
        row.checkVisible = false;
      } else {
        row.taskVisible = false;
        if (row.projectName != "" && row.projectName != undefined) {
          this.taskCheckTab(row);
        } else {
          row.proVisible = true;
        }
      }
      // 创建项目内的列表 任务名字也不能相同
    },
    // 关闭对话框
    closeDialog() {
      this.$emit("closeDialog");
    },
    closeDialogCan() {
      this.$emit("closeDialog", "1");
    },
    // 点击对话框事件
    clickDialog(e) {
      console.log(e);
    },
    // 关闭配置时间 嵌套对话框
    closeInnerDialog() {
      this.taskCreatedBatchInnerDialogVisible = false;
    },
  },
};
</script>

<style lang="less" scoped>
// .el-dialog {
//   position: relative;
// }
.main {
  display: block;
  position: relative;
}
// .redInput {
// border-radius: 3px;
// border: 1px solid red;
// color: red;
// outline: none;
// }
</style>